package cn.chiship.commons.util;
import java.util.Date;
import java.util.HashMap;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * 属性文件读取工具
 * @author lj
 * @time 2017.12.6
 */
public class PropertiesUtil {

    private static HashMap<String, PropertiesUtil> configMap = new HashMap<>(1);

    private Date loadTime = null;
    private ResourceBundle resourceBundle = null;
    private static final String NAME = "config";

    private static final Integer TIME_OUT = 60 * 1000;

    private PropertiesUtil(String name) {
        this.loadTime = new Date();
        this.resourceBundle = ResourceBundle.getBundle(name);
    }

    public static synchronized PropertiesUtil getInstance() {
        return getInstance(NAME);
    }

    public static synchronized PropertiesUtil getInstance(String name) {
        PropertiesUtil conf = configMap.get(name);
        if (null == conf) {
            conf = new PropertiesUtil(name);
            configMap.put(name, conf);
        }
        /**
         * 判断是否打开的资源文件是否超时1分钟
         */
        if ((System.currentTimeMillis()- conf.getLoadTime().getTime()) > TIME_OUT) {
            conf = new PropertiesUtil(name);
            configMap.put(name, conf);
        }
        return conf;
    }

    /**
     * 根据key读取value
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            String value = resourceBundle.getString(key);
            return value;
        }catch (MissingResourceException e) {
            return "";
        }
    }

    /**
     * 根据key读取value(整型)
     * @param key
     * @return
     */
    public Integer getInt(String key) {
        try {
            String value = resourceBundle.getString(key);
            return Integer.parseInt(value);
        }catch (MissingResourceException e) {
            return null;
        }
    }

    /**
     * 根据key读取value(布尔)
     * @param key
     * @return
     */
    public boolean getBool(String key) {
        try {
            String value = resourceBundle.getString(key);
            if ("true".equals(value)) {
                return true;
            }
            return false;
        }catch (MissingResourceException e) {
            return false;
        }
    }

    public Date getLoadTime() {
        return loadTime;
    }

    public static void main(String [] args){
        System.out.println(PropertiesUtil.getInstance("log4j").get("log4j.logger.org.hibernate.type"));


    }

}
